<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table,
        table tr th,
        table tr td {
            border: 1px solid #0094ff;
            text-align: center;
        }
    </style>
</head>

<body>
    <div>
        <input type="text" id="username" />
        <input type="radio" id="sexOne" name="sex" value="男" />男
        <input type="radio" id="sexTwo" checked name="sex" value="女" />女
        <input type="text" id="age" />
        <button id="add">添加</button>
    </div>
    <br />
    <table cellspacing="0" border="1" width="600px">
        <tr>
            <td>name</td>
            <td>sex</td>
            <td>age</td>
        </tr>
    </table>
    <script>
        //页面上输入用户的姓名、性别、年龄 确认后 列表的方式显示添加的数据
        //提示：取出input对应的dom对象后可以通过values属性获取到input中的内容
        let arrStu = []
        let table = document.querySelector('table')
        document.querySelector('#add').onclick = () => {
            let name = document.querySelector('#username').value
            let sex = document.querySelector('input[name="sex"]:checked').value
            let age = document.querySelector('#age').value
            console.log(name, sex, age);
            arrStu.push({ name: name, sex: sex, age: age })
            //渲染页面
            table.innerHTML = '';
            arrStu.forEach((v, index) => {
                //渲染表头
                if (index == 0) {
                    for (const key in v) {
                        let th = document.createElement('th')
                        th.innerText = key
                        table.appendChild(th)
                    }
                }
                //渲染内容
                let tr = document.createElement('tr')
                table.appendChild(tr)
                for (const key in v) {
                    let td = document.createElement('td')
                    td.innerText = v[key]
                    tr.appendChild(td)
                }
            });
        }


    </script>
</body>